package com.jcark.ui.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.jcark.ui.R;
import com.jcark.ui.utils.ViewUtils;

public class LoadingDialog extends Dialog {
    private Context context;
    private RotateAnimation rotateAnimation;

    public LoadingDialog(@NonNull Context context) {
        super(context, R.style.baseLoading);
        this.context = context;
        initView();
    }

    private void initView() {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_loading, null);
        setContentView(view);
        ImageView ivLoading = view.findViewById(R.id.iv_loading);

        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.width = ViewUtils.dpToPx(context, 48f);
        params.height = ViewUtils.dpToPx(context, 48f);
        getWindow().setAttributes(params);
        getWindow().setGravity(Gravity.CENTER);
        setCanceledOnTouchOutside(false);

        rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        rotateAnimation.setDuration(600);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setRepeatMode(Animation.RESTART);
        //让旋转动画一直转，不停顿的重点
        rotateAnimation.setInterpolator(new LinearInterpolator());
        rotateAnimation.setRepeatCount(-1);
        ivLoading.startAnimation(rotateAnimation);

        setOnKeyListener(keylistener);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (null != rotateAnimation) {
                    rotateAnimation.cancel();
                }
            }
        });
    }

    OnKeyListener keylistener = new OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };
}
